package com.qf.web.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.qf.entity.Result;
import com.qf.service.BusinessService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private BusinessService businessService;

    @GetMapping("/getBusinessReportData")
    public Result getBusinessData() throws InterruptedException {

        Map<String,Object> data = businessService.getData();
        data.put("reportDate",new Date());


        return Result.success(data);
    }

    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse resp) throws InterruptedException, IOException {
        //获取报表数据
        Map<String,Object> data = businessService.getData();
        data.put("date",new Date());
        //模拟热门套餐的集合数据(正常应该是去数据库查询)
        List<Map> list = new ArrayList<>();
        Map map1 = new HashMap();
        map1.put("setmealname","套餐1");
        map1.put("setmealcount","100");
        map1.put("percent","40%");

        Map map2 = new HashMap();
        map2.put("setmealname","套餐2");
        map2.put("setmealcount","200");
        map2.put("percent","20%");
        list.add(map1);
        list.add(map2);

        //基于easyexcel将数据库数据，填充到excel文件中
        String realPath = req.getServletContext().getRealPath("/uploadfiles");
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "aaa.xlsx";
        File destFile = new File(realPath,fileName);

        String templatePath = req.getServletContext().getRealPath("/template") + "/report_template.xlsx";
        //基于模板获取到一个写数据的构建器对象
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(destFile).withTemplate(templatePath);
        //基于构建器对象获取要写出的sheet
        WriteSheet sheet = excelWriterBuilder.sheet().build();
        //填充数据(填充map数据)
        ExcelWriter excelWriter = excelWriterBuilder.build();
        excelWriter.fill(data,sheet);
        //填充列表数据
        excelWriter.fill(list,sheet);

        //关闭excelWriter
        excelWriter.finish();

        //将得到的excel文件，以文件下载方式，下载到客户端本地(文件下载)
        /*
            两个头，一个流
            content-type  设置文件的mime类型
            content-disposition  设置浏览器以附件形式下载
            要下载的那个文件对应的输入流
         */
        resp.setHeader("content-type",req.getServletContext().getMimeType(fileName));
        resp.setHeader("content-disposition","attachment;filename=" + fileName);

        InputStream is = new FileInputStream(destFile);
        ServletOutputStream os = resp.getOutputStream();
        byte[] bys = new byte[1024];
        int len = -1;
        while((len = is.read(bys)) != -1){
            os.write(bys,0,len);
        }

        is.close();
    }

    @GetMapping("/exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest req,HttpServletResponse resp) throws InterruptedException, JRException, IOException {
        //获取报表数据
        Map<String,Object> data = businessService.getData();
        data.put("reportDate",new Date());
        //模拟热门套餐的集合数据(正常应该是去数据库查询)
        List<Map> list = new ArrayList<>();
        Map map1 = new HashMap();
        map1.put("name","套餐1");
        map1.put("setmeal_count","100");
        map1.put("proportion","40%");

        Map map2 = new HashMap();
        map2.put("name","套餐2");
        map2.put("setmeal_count","200");
        map2.put("proportion","20%");
        list.add(map1);
        list.add(map2);

        //基于jasper，生成pdf报表
        String templatePath = req.getServletContext().getRealPath("/template") + "/health_business3.jrxml";
        String destPath = req.getServletContext().getRealPath("/template") + "/health_business3.jasper";

        //将jrxml模板文件进行编译，得到jasper文件
        JasperCompileManager.compileReportToFile(templatePath,destPath);

        //向jasper文件中填充数据（data是非列表数据，JRBeanCollectionDataSource是列表数据）
        JasperPrint jasperPrint = JasperFillManager.fillReport(destPath, data, new JRBeanCollectionDataSource(list));

        String realPath = req.getServletContext().getRealPath("/uploadfiles");
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
        String destFilePath = realPath + "/" + fileName;
        //将填充完数据后的jasper文件，导出到指定pdf文件中
        JasperExportManager.exportReportToPdfFile(jasperPrint,destFilePath);


        //下载pdf文件
        resp.setHeader("content-type",req.getServletContext().getMimeType(fileName));
        resp.setHeader("content-disposition","attachment;filename=" + fileName);

        InputStream is = new FileInputStream(destFilePath);
        ServletOutputStream os = resp.getOutputStream();
        byte[] bys = new byte[1024];
        int len = -1;
        while((len = is.read(bys)) != -1){
            os.write(bys,0,len);
        }

        is.close();
    }

}
